/** 
 * @Description: 文件描述
 * @Author: 程前
 * @Date: 2025-01-02 15:32:32
 * @LastEditors: 程前
 * @LastEditTime: 2025-01-22 11:13:36
 */
import { Viewer, ScreenSpaceEventHandler, ScreenSpaceEventType, Cartesian3, Entity, Color, LabelStyle, VerticalOrigin, HorizontalOrigin, Cartesian2, ColorMaterialProperty, Cartographic, HeightReference, CallbackProperty, Ray, GeometryInstance, EllipseGeometry, GroundPrimitive, Primitive, PerInstanceColorAppearance, ColorGeometryInstanceAttribute, PolylineGeometry, VertexFormat, PrimitiveCollection, Matrix3, GroundPolylineGeometry, GroundPolylinePrimitive, PolylineMaterialAppearance, Material, Rectangle, ClassificationType, sampleTerrainMostDetailed, RectangleGeometry, RectangleOutlineGeometry, NearFarScalar, PolygonHierarchy, Math as CesiumMath } from "cesium";
import { setEventByHandler, removeEventByHandler, transformCartesianToWGS84 } from "@/utils"
import { createPrimitiveCircle } from "@/utils/cesium/primitive"
import { FloodAnalysis } from "@/cesium/tool/analysis/flood/Index";
import { BufferAnalysis } from "@/cesium/tool/analysis/buffer";
import { circle as TurfCircle, destination as TurfDestination, point as TurfPoint, booleanPointInPolygon, polygon as TurfPolygon } from "@turf/turf"
import { TrackMatte } from "./analysis/radar/trackMatte";

interface AnalysisInstance {
    clear: () => void;
}

interface DestroyableEntity {
    destroy: () => void;
    isCustomEntity?: boolean;
}

export default class AnalysisTools {
    viewer: Viewer;
    handler: ScreenSpaceEventHandler;
    tool: string; // 当前分析工具类型
    positions: Cartesian3[]; // 存储点位
    tempEntities: Entity[]; // 临时实体
    analysisInstances: AnalysisInstance[]; // 分析实例
    isDrawing: boolean; // 是否正在绘制
    tempPosition: Cartesian3 | null = null;
    lineList: Entity[] = [];
    circleList: Entity[] = [];
    private currentLine: Entity | null = null;
    private currentCircle: Entity | null = null;
    private worker: Worker | null = null;
    private radius: number = 0;
    private primitives: PrimitiveCollection;
    private currentCirclePrimitive: Primitive | null = null;
    private viewshedPrimitives: (Primitive | GroundPrimitive | GroundPolylinePrimitive)[] = [];

    constructor(viewer: Viewer, handler: ScreenSpaceEventHandler, tool: string) {
        this.viewer = viewer;
        this.handler = handler
        this.tool = tool
        this.positions = [];
        this.tempEntities = [];
        this.analysisInstances = [];
        this.isDrawing = false;
        // this.initWorker();
        this.primitives = new PrimitiveCollection();
        this.viewer.scene.primitives.add(this.primitives);
    }

    // private initWorker() {
    //     this.worker = new Worker(new URL('./wokers/viewshedWorker.ts', import.meta.url));
    //     this.worker.onmessage = (e) => {
    //         this.handleWorkerResult(e.data);
    //     };
    // }

    /**
     * 初始化鼠标事件
     */
    public initEvents(): void {
        if (this.tool === 'line' || this.tool === 'lines') {
            this.initLineViewshed();
        } else if (this.tool === 'circle') {
            this.initCircleViewshed();
        } else if (this.tool === 'contour') {
            this.initContourAnalysis();
        } else if (this.tool === 'flood') {
            this.initFloodAnalysis();
        } else if (this.tool === 'pointBuffer') {
            this.initBufferAnalysis('point');
        } else if (this.tool === 'lineBuffer') {
            this.initBufferAnalysis('line');
        } else if (this.tool === 'radar') {
            this.initRadarAnalysis();
        }
    }

    /**
     * 直线通视
     */
    private initLineViewshed(): void {
        this.isDrawing = true;

        // 创建动态线实体
        const createDynamicLine = () => {
            if (this.currentLine) {
                this.viewer.entities.remove(this.currentLine);
            }
            this.currentLine = this.viewer.entities.add({
                polyline: {
                    positions: new CallbackProperty(() => {
                        return this.tempPosition ?
                            [this.positions[0], this.tempPosition] :
                            []
                    }, false),
                    width: 2,
                    material: Color.YELLOW,
                    clampToGround: true
                }
            });
            return this.currentLine;
        };

        // 鼠标左键点击事件
        const leftClick = (event: any) => {
            const cartesian = this.viewer.scene.pickPosition(event.position);
            if (!cartesian) return;
            createDynamicLine();
            this.positions.push(cartesian);

            // 添加点实体
            const pointEntity = this.viewer.entities.add({
                position: cartesian,
                point: {
                    pixelSize: 8,
                    color: Color.GREEN.withAlpha(0.8),
                    outlineColor: Color.WHITE,
                    outlineWidth: 0,
                    heightReference: HeightReference.CLAMP_TO_GROUND
                }
            });
            this.tempEntities.push(pointEntity);

            // 如果已经有两个点，则计算通视
            if (this.positions.length === 2) {
                this.calculateViewshed(this.positions[0], this.positions[1]);
                if (this.tool === 'line') {
                    this.positions = [];
                } else {
                    this.positions.splice(1, 1);
                }
                this.currentLine = null;
                this.tempPosition = null;
                this.isDrawing = true; // 保持绘制状态为true，允许继续绘制
            }
        };
        setEventByHandler(this.handler, leftClick, ScreenSpaceEventType.LEFT_CLICK);

        // 鼠标移动事件
        const mouseMove = (event: any) => {
            if (this.positions.length === 0) return;
            const cartesian = this.viewer.scene.pickPosition(event.endPosition);
            if (cartesian) {
                this.tempPosition = cartesian;
            }
        };
        setEventByHandler(this.handler, mouseMove, ScreenSpaceEventType.MOUSE_MOVE);
    }

    /**
     * 找到第一个视线被阻挡的点
     */
    private findFirstBreakPoint(startPoint: Cartesian3, endPoint: Cartesian3): Cartesian3 | null {
        // 创建射线方向
        const direction = Cartesian3.subtract(endPoint, startPoint, new Cartesian3());
        Cartesian3.normalize(direction, direction);

        // 创建射线
        const ray = new Ray(startPoint, direction);

        // 检查射线是否与地形相交
        const intersection = this.viewer.scene.globe.pick(ray, this.viewer.scene);

        // 如果有交点，且交点在终点之前，说明找到了遮挡点
        if (intersection) {
            const intersectionDistance = Cartesian3.distance(startPoint, intersection);
            const totalDistance = Cartesian3.distance(startPoint, endPoint);

            if (intersectionDistance < totalDistance) {
                return intersection;
            }
        }

        return null;
    }

    /**
     * 计算通视结果并绘制线段
     */
    private calculateViewshed(startPoint: Cartesian3, endPoint: Cartesian3): void {
        // 获取第一个遮挡点
        const breakPoint = this.findFirstBreakPoint(startPoint, endPoint);
        const totalDistance = Cartesian3.distance(startPoint, endPoint);

        if (breakPoint) {
            const visibleDistance = Cartesian3.distance(startPoint, breakPoint);

            // 绘制可视部分（绿色）
            this.addLine(startPoint, breakPoint, Color.GREEN)

            // 绘制不可视部分（红色）
            this.addLine(breakPoint, endPoint, Color.RED)

            // 添加距离标签
            const labelPosition = Cartesian3.lerp(startPoint, endPoint, 0.5, new Cartesian3());
            const distanceLabel = this.viewer.entities.add({
                position: labelPosition,
                label: {
                    text: `总距离: ${totalDistance.toFixed(2)}米\n通视距离: ${visibleDistance.toFixed(2)}米`,
                    font: '20px sans-serif',
                    fillColor: Color.WHITE,
                    outlineColor: Color.BLACK,
                    outlineWidth: 2,
                    style: LabelStyle.FILL_AND_OUTLINE,
                    verticalOrigin: VerticalOrigin.BOTTOM,
                    pixelOffset: new Cartesian2(0, -10),
                    heightReference: HeightReference.CLAMP_TO_GROUND
                }
            });
            this.tempEntities.push(distanceLabel);
        } else {
            // 如果没有遮挡点，绘制全程可视的线段（绿色）
            this.addLine(startPoint, endPoint, Color.GREEN)

            // 添加距离标签
            const labelPosition = Cartesian3.lerp(startPoint, endPoint, 0.5, new Cartesian3());
            const distanceLabel = this.viewer.entities.add({
                position: labelPosition,
                label: {
                    text: `总距离: ${totalDistance.toFixed(2)}米\n通视距离: ${totalDistance.toFixed(2)}米`,
                    font: '20px sans-serif',
                    fillColor: Color.WHITE,
                    outlineColor: Color.BLACK,
                    outlineWidth: 2,
                    style: LabelStyle.FILL_AND_OUTLINE,
                    verticalOrigin: VerticalOrigin.BOTTOM,
                    pixelOffset: new Cartesian2(0, -10),
                    heightReference: HeightReference.CLAMP_TO_GROUND
                }
            });
            this.tempEntities.push(distanceLabel);
        }
    }

    private clearViewshedPrimitives(): void {
        this.viewshedPrimitives.forEach(primitive => {
            this.primitives.remove(primitive);
        });
        this.viewshedPrimitives = [];
    }

    /**
     * 圆形通视
     */
    private initCircleViewshed(): void {
        this.isDrawing = true;
        let center: Cartesian3 | null = null;
        let radius = 0;
        let dynamicRing: GroundPolylinePrimitive | null = null;
        let lastUpdateTime = 0;
        const UPDATE_THRESHOLD = 50; // 50ms的更新阈值

        // 创建动态圆实体
        const createDynamicCircle = (center: Cartesian3, radius?: number) => {
            // 如果是动态更新（鼠标移动时）
            if (!radius) {
                const currentTime = Date.now();
                // 限制更新频率
                if (currentTime - lastUpdateTime < UPDATE_THRESHOLD) {
                    return null;
                }
                lastUpdateTime = currentTime;

                // 清理之前的动态圆环
                if (dynamicRing) {
                    this.primitives.remove(dynamicRing);
                }

                const ringGeometry = new GeometryInstance({
                    geometry: new GroundPolylineGeometry({
                        positions: this.computeCirclePoints(center, this.radius, 180), // 减少点数以提高性能
                        width: 4
                    })
                });

                dynamicRing = new GroundPolylinePrimitive({
                    geometryInstances: ringGeometry,
                    appearance: new PolylineMaterialAppearance({
                        material: Material.fromType('Color', {
                            color: Color.GREEN.withAlpha(0.7)
                        })
                    }),
                    asynchronous: false // 设置为同步创建，避免闪烁
                });

                this.primitives.add(dynamicRing);
                return null;
            }

            // 如果是最终确定的圆（第二次点击时）
            const finalPositions = this.computeCirclePoints(center, this.radius, 360); // 最终圆使用更多的点以获得更好的效果
            const ringGeometry = new GeometryInstance({
                geometry: new GroundPolylineGeometry({
                    positions: finalPositions,
                    width: 4
                })
            });

            const groundRing = new GroundPolylinePrimitive({
                geometryInstances: ringGeometry,
                appearance: new PolylineMaterialAppearance({
                    material: Material.fromType('Color', {
                        color: Color.GREEN.withAlpha(0.7)
                    })
                }),
                asynchronous: false
            });

            this.primitives.add(groundRing);
            this.viewshedPrimitives.push(groundRing);
            this.radius = 0;
            return null;
        };


        // 创建放射状线条
        const createRadialLines = (center: Cartesian3, radius: number) => {
            const angleStep = 10;
            const centerPoint = transformCartesianToWGS84(center);

            // 使用turf计算终点位置
            for (let angle = 0; angle < 360; angle += angleStep) {
                const endPoint = TurfDestination(
                    TurfPoint([centerPoint.lng, centerPoint.lat]),
                    radius,
                    angle,
                    { units: 'meters' }
                );

                // 将计算出的终点坐标转换为Cesium的Cartesian3
                const endCartesian = Cartesian3.fromDegrees(
                    endPoint.geometry.coordinates[0],
                    endPoint.geometry.coordinates[1],
                    centerPoint.alt
                );

                // 射线版通视
                this.simpleViewshed(center, endCartesian);
            }
        };

        // 鼠标左键点击事件
        const leftClick = (event: any) => {
            const cartesian = this.viewer.scene.pickPosition(event.position);
            if (!cartesian) return;

            if (!center) {
                center = cartesian;
                this.positions.push(cartesian);
                // 添加圆心点实体
                const pointEntity = this.viewer.entities.add({
                    position: cartesian,
                    point: {
                        pixelSize: 8,
                        color: Color.GREEN.withAlpha(0.8),
                        outlineColor: Color.WHITE,
                        outlineWidth: 0
                    }
                });
                this.tempEntities.push(pointEntity);
                createDynamicCircle(center);
            } else {
                radius = Cartesian3.distance(center, cartesian);
                if (dynamicRing) {
                    this.primitives.remove(dynamicRing);
                    dynamicRing = null;
                }
                createDynamicCircle(center, radius);
                createRadialLines(center, radius);

                // 重置状态
                this.positions = [];
                center = null;
                this.tempPosition = null;
                this.isDrawing = true; // 保持绘制状态为true，允许继续绘制
            }
        };
        setEventByHandler(this.handler, leftClick, ScreenSpaceEventType.LEFT_CLICK);

        // 鼠标移动事件
        const mouseMove = (event: any) => {
            if (this.positions.length === 0) return;
            const cartesian = this.viewer.scene.pickPosition(event.endPosition);
            if (cartesian && center) {
                this.tempPosition = cartesian;
                // 动态更新圆的半径
                this.radius = Cartesian3.distance(center, cartesian);
                createDynamicCircle(center);
            }
        };
        setEventByHandler(this.handler, mouseMove, ScreenSpaceEventType.MOUSE_MOVE);
    }



    /**
     * 简易版直线通视分析
     * @param startPoint 起点
     * @param endPoint 终点
     */
    public simpleViewshed(startPoint: Cartesian3, endPoint: Cartesian3): void {
        // 计算射线方向
        const direction = Cartesian3.subtract(endPoint, startPoint, new Cartesian3());
        Cartesian3.normalize(direction, direction);

        // 创建射线
        const ray = new Ray(startPoint, direction);

        // 计算射线与地形的交点
        const intersectionPoint = this.viewer.scene.globe.pick(ray, this.viewer.scene);

        // 如果找到交点，判断交点是否在起点和终点之间
        if (intersectionPoint) {
            const intersectionDistance = Cartesian3.distance(startPoint, intersectionPoint);
            const totalDistance = Cartesian3.distance(startPoint, endPoint);

            // 只有当交点在起点和终点之间时，才认为有遮挡
            if (intersectionDistance < totalDistance) {
                // 绘制可视部分（绿色）
                this.addLine(startPoint, intersectionPoint, Color.GREEN)

                // 绘制不可视部分（红色）
                this.addLine(intersectionPoint, endPoint, Color.RED)

            } else {
                // 如果交点在终点之后，说明全程可视
                this.addLine(startPoint, endPoint, Color.GREEN)
            }
        } else {
            // 如果没有交点，说明全程可视
            this.addLine(startPoint, endPoint, Color.GREEN)
        }
    }

    /**
     * 根据圆心和半径生成圆坐标
     * @param center 
     * @param radius 
     * @param segments 
     */
    private computeCirclePoints(center: Cartesian3, radius: number, segments: number): Cartesian3[] {
        const positions: Cartesian3[] = [];

        // 使用turf创建圆
        const centerCircle = transformCartesianToWGS84(center)
        const turfCircle = TurfCircle([centerCircle.lng, centerCircle.lat], radius, {
            steps: segments,
            units: 'meters'
        });

        // 获取圆上的所有坐标点
        const coordinates = turfCircle.geometry.coordinates[0];
        coordinates.forEach(coord => {
            const point = Cartesian3.fromDegrees(
                coord[0],
                coord[1],
                centerCircle.alt
            );
            positions.push(point);
        });

        return positions;
    };


    /**
     * 绘线
     * @param startPoint 
     * @param endPoint 
     * @param color 
     */
    private addLine(startPoint: Cartesian3, endPoint: Cartesian3, color: Color) {
        const line = this.viewer.entities.add({
            polyline: {
                positions: [startPoint, endPoint],
                width: 3,
                material: color,
                clampToGround: true
            }
        });
        this.tempEntities.push(line);
    }

    /**
     * 等高线分析
     */
    private initContourAnalysis(): void {
        this.isDrawing = true;
        let startPosition: Cartesian3 | null = null;

        // 清理之前的实体
        this.tempEntities.forEach(entity => {
            this.viewer.entities.remove(entity);
        });
        this.tempEntities = [];

        // 清理之前的分析实例
        this.analysisInstances.forEach(instance => {
            instance.clear();
        });
        this.analysisInstances = [];

        // 创建动态矩形
        const createDynamicRectangle = () => {
            const rectangleEntity = this.viewer.entities.add({
                rectangle: {
                    coordinates: new CallbackProperty(() => {
                        if (!startPosition || !this.tempPosition) return undefined;

                        // 获取起点和终点的经纬度
                        const startCartographic = Cartographic.fromCartesian(startPosition);
                        const endCartographic = Cartographic.fromCartesian(this.tempPosition);

                        // 创建矩形
                        return new Rectangle(
                            Math.min(startCartographic.longitude, endCartographic.longitude),
                            Math.min(startCartographic.latitude, endCartographic.latitude),
                            Math.max(startCartographic.longitude, endCartographic.longitude),
                            Math.max(startCartographic.latitude, endCartographic.latitude)
                        );
                    }, false),
                    material: Color.YELLOW.withAlpha(0.2),
                    outline: true,
                    outlineColor: Color.YELLOW,
                    outlineWidth: 2,
                    classificationType: ClassificationType.TERRAIN
                }
            });
            this.currentLine = rectangleEntity;
            return rectangleEntity;
        };

        // 鼠标左键点击事件
        const leftClick = (event: any) => {
            const cartesian = this.viewer.scene.pickPosition(event.position);
            if (!cartesian) return;

            if (!startPosition) {
                startPosition = cartesian;
                this.positions.push(cartesian);
                createDynamicRectangle();
            } else {
                this.tempPosition = cartesian;

                // 获取当前矩形的坐标
                const rect = (this.currentLine?.rectangle?.coordinates as CallbackProperty)
                    .getValue(this.viewer.clock.currentTime);

                if (rect) {
                    // 移除entity矩形
                    if (this.currentLine) {
                        this.viewer.entities.remove(this.currentLine);
                    }

                    // 创建矩形边框的四个顶点
                    const west = rect.west;
                    const south = rect.south;
                    const east = rect.east;
                    const north = rect.north;

                    // 创建四条边的线段
                    const createBorderLine = (positions: Cartesian3[]) => {
                        return new GroundPolylinePrimitive({
                            geometryInstances: new GeometryInstance({
                                geometry: new GroundPolylineGeometry({
                                    positions: positions,
                                    width: 2
                                }),
                            }),
                            appearance: new PolylineMaterialAppearance({
                                material: Material.fromType('Color', {
                                    color: Color.YELLOW
                                })
                            })
                        });
                    };

                    // 创建四条边
                    const bottomLine = createBorderLine([
                        Cartesian3.fromRadians(west, south),
                        Cartesian3.fromRadians(east, south)
                    ]);
                    const rightLine = createBorderLine([
                        Cartesian3.fromRadians(east, south),
                        Cartesian3.fromRadians(east, north)
                    ]);
                    const topLine = createBorderLine([
                        Cartesian3.fromRadians(east, north),
                        Cartesian3.fromRadians(west, north)
                    ]);
                    const leftLine = createBorderLine([
                        Cartesian3.fromRadians(west, north),
                        Cartesian3.fromRadians(west, south)
                    ]);

                    // 添加所有primitive
                    this.primitives.add(bottomLine);
                    this.primitives.add(rightLine);
                    this.primitives.add(topLine);
                    this.primitives.add(leftLine);

                    // 保存引用以便后续清理
                    this.viewshedPrimitives.push(bottomLine);
                    this.viewshedPrimitives.push(rightLine);
                    this.viewshedPrimitives.push(topLine);
                    this.viewshedPrimitives.push(leftLine);

                    // 生成等高线
                    this.generateContours(rect).catch(error => {
                        console.error('生成等高线失败:', error);
                    });

                    // 重置状态
                    this.positions = [];
                    startPosition = null;
                    this.tempPosition = null;
                    this.currentLine = null;
                    this.isDrawing = true; // 保持绘制状态为true，允许继续绘制
                }
            }
        };
        setEventByHandler(this.handler, leftClick, ScreenSpaceEventType.LEFT_CLICK);

        // 鼠标移动事件
        const mouseMove = (event: any) => {
            if (!startPosition) return;
            const cartesian = this.viewer.scene.pickPosition(event.endPosition);
            if (cartesian) {
                this.tempPosition = cartesian;
            }
        };
        setEventByHandler(this.handler, mouseMove, ScreenSpaceEventType.MOUSE_MOVE);
    }

    private async generateContours(rect: Rectangle) {
        try {
            console.log('开始生成等高线...');

            // 增加采样点以提高精度
            const sampleCount = 100;
            const heightMap: number[][] = [];
            const positions: Cartographic[] = [];

            console.log('准备采样点...');
            // 准备采样点
            for (let i = 0; i <= sampleCount; i++) {
                heightMap[i] = [];
                for (let j = 0; j <= sampleCount; j++) {
                    const lon = rect.west + (rect.east - rect.west) * (j / sampleCount);
                    const lat = rect.south + (rect.north - rect.south) * (i / sampleCount);
                    positions.push(new Cartographic(lon, lat));
                }
            }

            console.log('获取高度数据...');
            // 批量获取高度
            const heights = await sampleTerrainMostDetailed(this.viewer.terrainProvider, positions);
            console.log('高度数据获取完成，数据点数：', heights.length);

            // 填充高度图
            let index = 0;
            let minHeight = Number.MAX_VALUE;
            let maxHeight = Number.MIN_VALUE;

            for (let i = 0; i <= sampleCount; i++) {
                heightMap[i] = [];
                for (let j = 0; j <= sampleCount; j++) {
                    const height = heights[index++].height || 0;
                    heightMap[i][j] = height;
                    minHeight = Math.min(minHeight, height);
                    maxHeight = Math.max(maxHeight, height);
                }
            }

            console.log('高度范围：', minHeight, '至', maxHeight);

            // 计算合适的等高线间隔
            const heightRange = maxHeight - minHeight;
            let contourInterval: number;

            // 根据高度范围动态调整间隔
            if (heightRange <= 50) {
                contourInterval = 5; // 平缓地形使用小间隔
            } else if (heightRange <= 100) {
                contourInterval = 10;
            } else if (heightRange <= 200) {
                contourInterval = 20;
            } else if (heightRange <= 500) {
                contourInterval = 50;
            } else {
                contourInterval = Math.ceil(heightRange / 15); // 确保至少有15条等高线
                contourInterval = Math.ceil(contourInterval / 50) * 50; // 向上取整到50的倍数
            }

            console.log('等高线间隔：', contourInterval, '米');

            // 调整起始高度，确保从整数高度开始
            const startHeight = Math.floor(minHeight / contourInterval) * contourInterval;
            console.log('起始高度：', startHeight);

            // 存储所有等高线段
            const contourSegments: Map<number, Array<Cartesian3[]>> = new Map();

            // 生成等高线
            for (let height = startHeight; height <= maxHeight; height += contourInterval) {
                console.log('生成高度为', height, '米的等高线');
                const segments: Array<Cartesian3[]> = [];
                let currentSegment: Cartesian3[] = [];

                // 遍历网格
                for (let i = 0; i < sampleCount; i++) {
                    for (let j = 0; j < sampleCount; j++) {
                        const h00 = heightMap[i][j];
                        const h10 = heightMap[i][j + 1];
                        const h01 = heightMap[i + 1][j];
                        const h11 = heightMap[i + 1][j + 1];

                        // 计算网格的经纬度范围
                        const x0 = rect.west + (rect.east - rect.west) * (j / sampleCount);
                        const x1 = rect.west + (rect.east - rect.west) * ((j + 1) / sampleCount);
                        const y0 = rect.south + (rect.north - rect.south) * (i / sampleCount);
                        const y1 = rect.south + (rect.north - rect.south) * ((i + 1) / sampleCount);

                        const intersectionPoints: Cartesian3[] = [];

                        // 检查每条边是否与等高线相交
                        // 左边
                        if ((h00 <= height && height < h01) || (h01 <= height && height < h00)) {
                            const t = (height - h00) / (h01 - h00);
                            const lat = y0 + (y1 - y0) * t;
                            intersectionPoints.push(Cartesian3.fromRadians(x0, lat, height));
                        }

                        // 右边
                        if ((h10 <= height && height < h11) || (h11 <= height && height < h10)) {
                            const t = (height - h10) / (h11 - h10);
                            const lat = y0 + (y1 - y0) * t;
                            intersectionPoints.push(Cartesian3.fromRadians(x1, lat, height));
                        }

                        // 上边
                        if ((h00 <= height && height < h10) || (h10 <= height && height < h00)) {
                            const t = (height - h00) / (h10 - h00);
                            const lon = x0 + (x1 - x0) * t;
                            intersectionPoints.push(Cartesian3.fromRadians(lon, y0, height));
                        }

                        // 下边
                        if ((h01 <= height && height < h11) || (h11 <= height && height < h01)) {
                            const t = (height - h01) / (h11 - h01);
                            const lon = x0 + (x1 - x0) * t;
                            intersectionPoints.push(Cartesian3.fromRadians(lon, y1, height));
                        }

                        // 如果找到两个交点，处理线段
                        if (intersectionPoints.length === 2) {
                            // 如果当前段为空，开始新的段
                            if (currentSegment.length === 0) {
                                currentSegment.push(...intersectionPoints);
                            } else {
                                // 检查是否可以连接到当前段
                                const lastPoint = currentSegment[currentSegment.length - 1];
                                const dist1 = Cartesian3.distance(lastPoint, intersectionPoints[0]);
                                const dist2 = Cartesian3.distance(lastPoint, intersectionPoints[1]);

                                const threshold = heightRange <= 50 ? 20 : 10; // 平缓地形使用更大的连接阈值
                                if (Math.min(dist1, dist2) < threshold) { // 如果距离小于阈值，连接线段
                                    if (dist1 < dist2) {
                                        currentSegment.push(intersectionPoints[1]);
                                    } else {
                                        currentSegment.push(intersectionPoints[0]);
                                    }
                                } else {
                                    // 如果不能连接，保存当前段并开始新的段
                                    if (currentSegment.length > 1) {
                                        segments.push([...currentSegment]);
                                    }
                                    currentSegment = [...intersectionPoints];
                                }
                            }
                        }
                    }
                }

                // 保存最后一段
                if (currentSegment.length > 1) {
                    segments.push(currentSegment);
                }

                if (segments.length > 0) {
                    contourSegments.set(height, segments);
                }
            }

            // 绘制等高线和添加标注
            const labelPositions = new Set<string>(); // 用于记录已添加标注的位置

            contourSegments.forEach((segments, height) => {
                segments.forEach(positions => {
                    if (positions.length < 2) return;

                    // 创建等高线
                    const line = this.viewer.entities.add({
                        polyline: {
                            positions: positions,
                            width: 2,
                            material: Color.fromCssColorString('#66CDAA').withAlpha(0.8),
                            clampToGround: true,
                            classificationType: ClassificationType.TERRAIN
                        }
                    });
                    this.tempEntities.push(line);
                });

                // 找到最长的线段用于添加标注
                const segmentForLabel = segments.reduce((longest, current) =>
                    current.length > longest.length ? current : longest, segments[0]);

                // 计算标注间隔距离（米）
                const minLabelDistance = heightRange <= 200 ? 200 : 500; // 根据高度范围调整最小间隔

                // 在最长的段上添加标注
                const points = segmentForLabel;
                let lastLabelPosition: Cartesian3 | null = null;

                // 每隔一定距离添加一个标注
                for (let i = 0; i < points.length; i++) {
                    const currentPoint = points[i];

                    // 检查是否需要添加标注
                    if (lastLabelPosition === null ||
                        Cartesian3.distance(lastLabelPosition, currentPoint) >= minLabelDistance) {

                        // 将位置转换为字符串用于去重
                        const posKey = `${currentPoint.x.toFixed(0)},${currentPoint.y.toFixed(0)}`;

                        // 检查附近是否已有标注
                        if (!labelPositions.has(posKey)) {
                            const label = this.viewer.entities.add({
                                position: currentPoint,
                                label: {
                                    text: height.toFixed(0) + 'm',
                                    font: '16px sans-serif',
                                    fillColor: Color.WHITE,
                                    outlineColor: Color.BLACK,
                                    outlineWidth: 2,
                                    style: LabelStyle.FILL_AND_OUTLINE,
                                    verticalOrigin: VerticalOrigin.CENTER,
                                    horizontalOrigin: HorizontalOrigin.CENTER,
                                    pixelOffset: new Cartesian2(0, -5),
                                    heightReference: HeightReference.CLAMP_TO_GROUND,
                                    disableDepthTestDistance: Number.POSITIVE_INFINITY,
                                    scale: 1.0,
                                    translucencyByDistance: new NearFarScalar(1000, 1.0, 5000, 0.8)
                                }
                            });
                            this.tempEntities.push(label);
                            lastLabelPosition = currentPoint;
                            labelPositions.add(posKey);
                        }
                    }
                }
            });

            console.log('等高线生成完成');
        } catch (error) {
            console.error('生成等高线失败:', error);
        }
    }

    /**
     * 淹没分析
     */
    private initFloodAnalysis(): void {
        this.isDrawing = true;
        let floodAnalysis: FloodAnalysis | null = null;

        // 清理之前的实体
        this.tempEntities.forEach(entity => {
            this.viewer.entities.remove(entity);
        });
        this.tempEntities = [];

        // 清理之前的分析实例
        this.analysisInstances.forEach(instance => {
            instance.clear();
        });
        this.analysisInstances = [];

        // 创建动态多边形
        const createDynamicPolygon = () => {
            const polygonEntity = this.viewer.entities.add({
                polygon: {
                    hierarchy: new CallbackProperty(() => {
                        if (this.positions.length < 2) return undefined;
                        return new PolygonHierarchy(
                            this.tempPosition ?
                                [...this.positions, this.tempPosition] :
                                this.positions
                        );
                    }, false),
                    material: Color.YELLOW.withAlpha(0.2),
                    outline: true,
                    outlineColor: Color.YELLOW,
                    outlineWidth: 2,
                    classificationType: ClassificationType.TERRAIN
                }
            });
            this.currentLine = polygonEntity;
            return polygonEntity;
        };

        // 鼠标左键点击事件
        const leftClick = (event: any) => {
            const cartesian = this.viewer.scene.pickPosition(event.position);
            if (!cartesian) return;

            this.positions.push(cartesian);

            // 添加点实体
            const pointEntity = this.viewer.entities.add({
                position: cartesian,
                point: {
                    pixelSize: 8,
                    color: Color.YELLOW,
                    outlineColor: Color.WHITE,
                    outlineWidth: 2,
                }
            });
            this.tempEntities.push(pointEntity);

            // 创建或更新动态多边形
            if (this.positions.length === 1) {
                createDynamicPolygon();
            }
        };
        setEventByHandler(this.handler, leftClick, ScreenSpaceEventType.LEFT_CLICK);

        // 鼠标移动事件
        const mouseMove = (event: any) => {
            if (this.positions.length === 0) return;
            const cartesian = this.viewer.scene.pickPosition(event.endPosition);
            if (cartesian) {
                this.tempPosition = cartesian;
            }
        };
        setEventByHandler(this.handler, mouseMove, ScreenSpaceEventType.MOUSE_MOVE);

        // 鼠标右键点击事件（完成绘制）
        const rightClick = () => {
            if (this.positions.length < 3) return; // 至少需要3个点才能形成多边形

            // 清除所有点标记
            this.tempEntities.forEach(entity => {
                this.viewer.entities.remove(entity);
            });
            this.tempEntities = this.tempEntities.filter(entity => !entity.point);

            // 移除动态多边形
            if (this.currentLine) {
                this.viewer.entities.remove(this.currentLine);
            }

            // 创建淹没分析实例
            if (floodAnalysis) {
                floodAnalysis.clear();
                floodAnalysis = null;
            }

            // 保存当前positions的副本用于分析
            const analysisPositions = [...this.positions];

            floodAnalysis = new FloodAnalysis({
                viewer: this.viewer,
                coordinates: analysisPositions,
                color: Color.WHITE,
                speed: 20.0,
                waterImg: undefined,
                onHeightChange: (height: number) => {
                    console.log('当前淹没高度:', height);
                },
                onComplete: () => {
                    console.log('淹没分析完成');
                }
            });

            // 开始淹没分析
            floodAnalysis.start();

            // 保存分析实例
            this.analysisInstances.push(floodAnalysis);

            // 重置状态（在创建分析实例后再清除）
            this.positions = [];
            this.tempPosition = null;
            this.currentLine = null;
        };
        setEventByHandler(this.handler, rightClick, ScreenSpaceEventType.RIGHT_CLICK);
    }

    /**
     * 初始化缓冲区分析
     */
    private initBufferAnalysis(type: 'point' | 'line'): void {
        // 清理之前的实体
        this.tempEntities.forEach(entity => {
            this.viewer.entities.remove(entity);
        });
        this.tempEntities = [];

        // 清理之前的分析实例
        this.analysisInstances.forEach(instance => {
            instance.clear();
        });
        this.analysisInstances = [];

        // 创建缓冲区分析实例
        const bufferAnalysis = new BufferAnalysis({
            viewer: this.viewer,
            type: type,
            radius: 100, // 默认100米
            color: Color.YELLOW.withAlpha(0.5)
        });

        // 开始绘制
        bufferAnalysis.startDraw();

        // 保存分析实例
        this.analysisInstances.push(bufferAnalysis);
    }

    /**
     * 雷达分析
     */
    private initRadarAnalysis(): void {
        this.isDrawing = true;

        // 鼠标左键点击事件
        const leftClick = (event: any) => {
            const cartesian = this.viewer.scene.pickPosition(event.position);
            if (!cartesian) return;

            // 清理之前的实体
            this.tempEntities.forEach(entity => {
                this.viewer.entities.remove(entity);
            });
            this.tempEntities = [];

            // 添加点实体
            const pointEntity = this.viewer.entities.add({
                position: cartesian,
                point: {
                    pixelSize: 8,
                    color: Color.GREEN.withAlpha(0.8),
                    outlineColor: Color.WHITE,
                    outlineWidth: 0,
                    heightReference: HeightReference.CLAMP_TO_GROUND
                }
            });
            this.tempEntities.push(pointEntity);

            // 获取点击位置的经纬度
            const cartographic = Cartographic.fromCartesian(cartesian);
            const longitude = CesiumMath.toDegrees(cartographic.longitude);
            const latitude = CesiumMath.toDegrees(cartographic.latitude);

            // 创建雷达实例
            const trackMatte = new TrackMatte({
                viewer: this.viewer,
                id: Date.now().toString(),
                range: 1000.0,
                position: [longitude, latitude],
            });

            // 将雷达实例添加到分析实例列表中
            this.analysisInstances.push({
                clear: () => {
                    // 清理雷达相关的实体
                    this.viewer.entities.removeById(trackMatte.id);
                }
            });
        };
        setEventByHandler(this.handler, leftClick, ScreenSpaceEventType.LEFT_CLICK);
    }

    /**
    * 销毁编辑器，清理所有实体和事件监听
    */
    public destroy(): void {
        // 清理所有视域分析相关的 primitives
        this.clearViewshedPrimitives();
        
        // 清理当前圆形 primitive
        if (this.currentCirclePrimitive) {
            this.primitives.remove(this.currentCirclePrimitive);
            this.currentCirclePrimitive = null;
        }
        
        // 清理所有临时实体
        this.tempEntities.forEach(entity => {
            this.viewer.entities.remove(entity);
        });
        this.tempEntities = [];

        // 清理所有分析实例的事件处理器
        this.analysisInstances.forEach(instance => {
            if (instance instanceof BufferAnalysis) {
                instance.destroyHandler();
            }
        });

        // 清理 primitives 集合
        if (this.primitives) {
            this.primitives.removeAll();
            this.viewer.scene.primitives.remove(this.primitives);
        }

        // 清理事件处理器
        if (this.handler) {
            this.handler.destroy();
        }

        // 重置所有状态
        this.positions = [];
        this.tempPosition = null;
        this.currentLine = null;
        this.currentCircle = null;
        this.isDrawing = false;
    }
}
